#!/usr/bin/python
# -*- coding: utf-8 -*-

#########################################
#                                       #
# plugin.video.seans-online-eu for xbmc #
# author: t0mus                         #
#                                       #
#########################################

""" XBMC plugin for seans-online.eu site """

import os
import sys
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcgui

__this_plugin__ = int(sys.argv[1])
reload(sys)
sys.setdefaultencoding('utf-8')

__addon__ = 'plugin.video.seans-online-eu'
__settings__ = xbmcaddon.Addon(id=__addon__)
__plugin_string__ = 'plugin://' + __addon__ + '/?'
__baseurl_string__ = 'http://seans-online.eu/'

__images_dir__ = \
    xbmc.translatePath(os.path.join(__settings__.getAddonInfo('path'),
                       'resources', 'images'))
__lib_dir__ = \
    xbmc.translatePath(os.path.join(__settings__.getAddonInfo('path'),
                       'resources', 'lib'))

sys.path.append(__lib_dir__)

from strings import __categories_string__, __search_string__, \
    __header_string__, __loadingcategories_string__, \
    __movietitle_string__, __loadingmovies_string__
from t0mus.common.common import *
from BeautifulSoup import BeautifulSoup

__tools__ = TOOLS()
__tools__.load_parameters(sys.argv[2])
__get__ = __tools__.get_cmd


def create_main_menu():
    """ Creates main menu."""

    browse = xbmcgui.ListItem(__categories_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2.png'))
    search = xbmcgui.ListItem(__search_string__,
                              iconImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'),
                              thumbnailImage=os.path.join(__images_dir__,
                              'Folder 2 Search.png'))
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'browse=true', browse, isFolder=True)
    xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                + 'search=true', search, isFolder=True)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)


def create_categories():
    """ Creates categories menu."""

    dialog = xbmcgui.DialogProgress()
    dialog.create(__header_string__, __loadingcategories_string__)
    count = 0
    soup = BeautifulSoup(open_url(__baseurl_string__).read())
    ul = soup.find(attrs={'id': 'left-box-cat'})
    links = ul.findAll('a')
    for cat in ul.findAll('li'):
        name = unescape(cat.string)
        link = __baseurl_string__[:-1]+links[count]['href']
        list_item = xbmcgui.ListItem(unescape(name))
        xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                    + 'category=' + link, list_item,
                                    isFolder=True)
        count = count + 1
        dialog.update(count * 10, __loadingcategories_string__)
    dialog.close()
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)


def add_movies(url):
    """ Adds list items representing movies."""

    dialog = xbmcgui.DialogProgress()
    count = 0
    dialog.create(__header_string__, __loadingmovies_string__)
    soup = BeautifulSoup(open_url(url).read())
    for wrapper in soup.findAll('div','right-box-film-list'):
        img=__baseurl_string__[:-1]+wrapper.find('img','brn')['src']
        div=wrapper.find('div','film-list-titile')
        title=div.find('a')
        name = unescape(title.string)
        link = __baseurl_string__[:-1]+title['href']
        list_item = xbmcgui.ListItem(name, iconImage=img)
        xbmcplugin.addDirectoryItem(__this_plugin__,
                __plugin_string__ + 'movie=' + link + '&name='
                + name, list_item, isFolder=True)
        count = count + 1
        dialog.update(count * 10, __loadingmovies_string__)
    dialog.close()
    return count


from t0mus.common.hosting import recognize_video_hosting

if __get__('category') != None:
    __category__ = str(__get__('category'))
    if __get__('page') != None:
        __page__ = int(__get__('page'))
    else:
        __page__ = 1
    __count__ = add_movies(__category__[:-5] + '-' + str(__page__)+'.html')
    if __count__ > 8:
        __nextp__ = __page__ + 1
        __nextPage__ = create_next_page_list_item(__page__, __count__,
                10)
        xbmcplugin.addDirectoryItem(__this_plugin__, __plugin_string__
                                    + 'category=' + __category__
                                    + '&page=' + str(__nextp__),
                                    __nextPage__, isFolder=True)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
elif __get__('movie') != None:
    __movie__ = str(__get__('movie'))
    __item_name__ = str(__get__('name'))
    recognize_video_hosting(__this_plugin__, __movie__, __item_name__)
    xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
elif __get__('browse') != None:
    create_categories()
elif __get__('search') != None:
    __text__ = None
    if __get__('query') != None:
        __text__ = __get__('query')
    else:
        __kb__ = xbmc.Keyboard('', __movietitle_string__, False)
        __kb__.doModal()
        if __kb__.isConfirmed():
            __text__ = __kb__.getText()

    if __text__ != None:
        if __get__('page') != None:
            __page__ = int(__get__('page'))
        else:
            __page__ = 1
        __count__ = add_movies(__baseurl_string__ + 'search,'
                               + __text__ + ',' + str(__page__)+'.html')
        if __count__ > 8:
            __nextp__ = __page__ + 1
            __nextPage__ = create_next_page_list_item(__page__,
                    __count__, 10)
            xbmcplugin.addDirectoryItem(__this_plugin__,
                    __plugin_string__ + 'search=true&query=' + __text__
                    + '&page=' + str(__nextp__), __nextPage__,
                    isFolder=True)
        xbmcplugin.endOfDirectory(__this_plugin__, succeeded=True)
else:
    create_main_menu()
